<template>
  <ElTreeSelect
    v-model="props.data[props.field.name]"
    :data="fieldOptions"
    :props="currentProps"
    :node-key="currentProps.value"
    :filterable="filterable"
    :clearable="clearable"
    :placeholder="placeholderText"
    :empty-text="placeholderText"
    :no-match-text="placeholderText"
    :empty-values="validEmptyValues"
    :loading="loading"
    :remote="remote"
	:multiple="props.field.multiple=='1'"
	:show-checkbox="props.field.multiple=='1'"
	:check-strictly="props.field.checkStrictly=='0'"
    :remote-method="remote ? remoteSearch : undefined"
    :filter-node-method="filterable ? filterNodeMethod : undefined"
	@clear="handleClear"
  />
</template>

<script lang="ts" setup>
import { computed, ref, watch } from 'vue'
import type { PropType } from 'vue'
import type { ElTreeSelect } from 'element-plus'

interface TreeNode {
  [key: string]: any
  children?: TreeNode[]
}

const emit = defineEmits(['update:value'])
const defaultProps = {
  children: 'children',
  label: 'label',
  value: 'id'
}

const props = defineProps({
  field: {
    type: Object as PropType<Record<string, any>>,
    required: true,
    default: () => ({})
  },
  data: {
    type: Object as PropType<Record<string, any>>,
    default: () => ({})
  },
  fetchOptions: {
    type: Function as PropType<(params?: any) => Promise<any>>,
    required: false
  },
  option: {
    type: Object as PropType<Record<string, any>>,
    default: () => ({})
  },
})

// 计算最终使用的属性配置
const currentProps = computed(() => props.option || defaultProps)

// 占位符文本
const placeholderText = computed(() => {
  return props.field.placeholder || `请选择${props.field.label || ''}`
})

// 处理 empty-values
const validEmptyValues = computed(() => {
  const values = new Set<any>([null, undefined, '']) // 默认空值
  
  // 添加配置的空值
  if (props.field?.emptyValues) {
    props.field.emptyValues.split(',').forEach((item:any) => {
      const trimmed = item.trim()
      if (trimmed === 'null') values.add(null)
      else if (trimmed === 'undefined') values.add(undefined)
      else if (trimmed !== '') values.add(trimmed)
    })
  }
  // 确保defaultValue在emptyValues中
  if (props.field?.defaultValue !== undefined) {
    values.add(props.field.defaultValue)
  }
  return Array.from(values)
})
// 关键修复：确保valueOnClear是emptyValues中的原始值
const validValueOnClear = computed(() => {
  // 1. 优先使用defaultValue
  if (props.field?.defaultValue !== undefined) {
    return props.field.defaultValue
  }
  // 2. 返回emptyValues中的第一个原始值
  return validEmptyValues.value.length > 0 
    ? validEmptyValues.value[0]
    : null
})

// 是否可清空
const clearable = computed(() => {
  return props.field.clearable ?? true
})

// 是否可过滤
const filterable = computed(() => {
  return props.field.filterable !== false && props.field.filterable !== '0'
})

// 是否远程搜索模式
const remote = computed(() => {
  return props.field.remote || false
})

const handleClear=()=>{
	props.data[props.field.name]=props.field.defaultValue;
}

// 选项数据
const fieldOptions = ref<TreeNode[]>(props.field.options || [])
const loading = ref(false)

// 双向绑定值
const fieldValue = computed({
  get: () => props.data[props.field.name],
  set: (value) => {
    emit('update:value', value)
  }
})

// 过滤节点方法
const filterNodeMethod = (value: string, data: TreeNode) => {
  if (!value) return true
  const labelKey = currentProps.value.label || 'label'
  return data[labelKey]?.toString().toLowerCase().includes(value.toLowerCase())
}

// 远程搜索方法
const remoteSearch = async (query: string) => {
  if (!props.fetchOptions) return
  
  loading.value = true
  try {
    const params = { ...props.field.params, keyword: query }
    const data = await props.fetchOptions(params)
    fieldOptions.value = Array.isArray(data) ? data : []
  } catch (error) {
    console.error('搜索失败', error)
    fieldOptions.value = []
  } finally {
    loading.value = false
  }
}

// 获取选项数据
const getFetchOptions = async (params?: any) => {
  if (!props.fetchOptions) return
  
  loading.value = true
  try {
    const data = await props.fetchOptions(params || props.field.params)
    fieldOptions.value = Array.isArray(data) ? data : []
  } catch (error) {
    console.error('数据加载失败', error)
    fieldOptions.value = []
  } finally {
    loading.value = false
  }
}

// 初始化加载选项
if (props.fetchOptions && !props.field.options) {
  getFetchOptions()
}

// 监听fetchOptions变化
watch(
  () => props.fetchOptions,
  (newVal) => {
    if (newVal && !props.field.options) {
      getFetchOptions()
    }
  },
  { immediate: true }
)

// 监听参数变化重新加载
watch(
  () => props.field.params,
  (newParams) => {
    if (props.fetchOptions && !props.field.options) {
      getFetchOptions(newParams)
    }
  },
  { deep: true }
)
</script>